package com.srwl.mytx.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.widget.UserDetailsDialog;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.UserService;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class LiveMessageAdapter extends RecyclerView.Adapter<LiveMessageAdapter.MyViewHolder> {
    private static final String TAG = "LiveMessageAdapter";
    private final Context context;

    List<Message> messages = new ArrayList<>();


    public LiveMessageAdapter(Context context, List<Message> messages) {
        this.context = context;
        this.messages = messages;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.layout_room_msgs_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        final Message message = messages.get(position);

        SpannableStringBuilder nickAndContent = new SpannableStringBuilder();
        nickAndContent.append(message.getTitle() == null ? "" : message.getTitle()).append(": ").append(message.getContent());    //设置内容
        ClickableSpan clickableSpan = new ClickableSpan() {     //设置Spannable中指定文字的点击事件
            @Override
            public void onClick(@NonNull View widget) {
                if (!Helper.getInstance().isNetworkConnected()) {
                    ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
                    return;
                }
                RetrofitManager.getInstance().createRequest(UserService.class)
                        .getUserInfo_v1(message.getFromId())
                        .enqueue(new Callback<CommonResult>() {
                            @Override
                            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                                CommonResult body = response.body();
                                if (!response.isSuccessful() || body == null) {
                                    Log.e(TAG, "onResponse: " + response.message());
                                    return;
                                }

                                if (body.isError()) {
                                    Log.e(TAG, "onResponse: " + body.getMsg());
                                    return;
                                }
                                JSONObject data = (JSONObject) body.getData();
                                User user = data.toJavaObject(User.class);
                                showUserDetailDialog(user);

                            }

                            @Override
                            public void onFailure(Call<CommonResult> call, Throwable t) {
                                Log.e(TAG, "onFailure: 获取用户信息错误");
                            }
                        });
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                //super.updateDrawState(ds);
                ds.setUnderlineText(false);     //取消掉响应事件的文字的下划线
            }
        };
        int length;

        if (message.getTitle() != null) {
            length = message.getTitle().length();
        } else {
            length = 0;
        }
        nickAndContent.setSpan(clickableSpan, 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        nickAndContent.setSpan(new ForegroundColorSpan(Color.parseColor("#50a7b9")), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
        nickAndContent.setSpan(styleSpan, 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);   //设置粗体
        holder.nameAndContent.setMovementMethod(LinkMovementMethod.getInstance());  //设置光标如何移动计量的方法，不配置这个给Spannable绑定事件是无效的
        //将扩展字符串设置进TextView中
        holder.nameAndContent.setText(nickAndContent);

        /*holder.name.setText(message.getTitle());
        holder.content.setText(message.getContent());
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!Helper.getInstance().isNetworkConnected()) {
                    ((BaseActivity)context).showToast_v1(context.getString(R.string.network_anomalies));
                    return;
                }
                RetrofitManager.getInstance().createRequest(UserService.class)
                        .getUserInfo_v1(message.getFromId())
                        .enqueue(new Callback<CommonResult>() {
                            @Override
                            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                                CommonResult body = response.body();
                                if (!response.isSuccessful() || body == null) {
                                    Log.e(TAG, "onResponse: " + response.message());
                                    return;
                                }

                                if (body.isError()) {
                                    Log.e(TAG, "onResponse: " + body.getMsg());
                                    return;
                                }
                                JSONObject data = (JSONObject) body.getData();
                                User user = data.toJavaObject(User.class);
                                showUserDetailDialog(user);

                            }

                            @Override
                            public void onFailure(Call<CommonResult> call, Throwable t) {
                                Log.e(TAG, "onFailure: 获取用户信息错误");
                            }
                        });
            }
        });*/
    }

    private void showUserDetailDialog(User user) {

        UserDetailsDialog detailsDialog_1 = new UserDetailsDialog(context, user);
        detailsDialog_1.setUserDetailsDialogListener(new UserDetailsDialog.UserDetailsDialogListener() {
            @Override
            public void onMentionClick(String username) {

            }

            @Override
            public void onMessageClick(User user) {
                context.startActivity(new Intent(context, ChatActivity.class).putExtra(Constant.EXTRA_TARGET_USER_INFO, user));
            }
        });
        detailsDialog_1.show();
    }

    @Override
    public int getItemCount() {
        return messages.size();
    }


    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        TextView content;
        TextView nameAndContent;

        private MyViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.tv_nick);
            content = itemView.findViewById(R.id.tv_content);
            nameAndContent = itemView.findViewById(R.id.tv_nick_and_content);
        }
    }
}

